import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import * as dayjs from 'dayjs';
import AvatarEntity from 'src/entities/avatar.entity';
import FeedBackImageEntity from 'src/entities/feed-back-image.entity';
import FeedBackEntity from 'src/entities/feed-back.entity';
import HoroscopeEntity from 'src/entities/horoscope.entity';
import SmsCodeEntity from 'src/entities/smscode.entity';
import UserCommemorationDayEntity from 'src/entities/user-commemoration-day.entity';
import UserExtendEntity from 'src/entities/user-extend.entity';
import UserLimitEntity from 'src/entities/user-limit.entity';
import UserLittleThingsEntity from 'src/entities/user-little-things.entity';
import UserSignDataEntity from 'src/entities/user-sign-data.entity';
import UserEntity from 'src/entities/user.entity';
import { uploadFile } from 'src/utils/file';
import { sendSms } from 'src/utils/sendSms';
import { RandomCode } from 'src/utils/utils';
import { EntityManager, Repository } from 'typeorm';
import { BindUserOtherHalfDTO, GetUserHoroscopeDTO, GetUserInfoByLoveCodeDTO, GetUserInfoBySysIDDTO, GetUserLimitDTO, GetUserLoveCodeDTO, GetUserOpenIDDTO, HandleUserDTO, RegisterUserDTO, SendRegisterSmsCodeDTO, SubmitFeedBackDTO, UploadAvatarDTO, UserSignInDTO } from './user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserExtendEntity)
    private readonly userExtendEntityRepository: Repository<UserExtendEntity>,
    @InjectRepository(UserEntity)
    private readonly userEntityRepository: Repository<UserEntity>,
    @InjectRepository(HoroscopeEntity)
    private readonly horoscopeEntityRepository: Repository<HoroscopeEntity>,
    @InjectRepository(UserLimitEntity)
    private readonly userLimitEntityRepository: Repository<UserLimitEntity>,
    @InjectRepository(SmsCodeEntity)
    private readonly smsCodeEntityRepository: Repository<SmsCodeEntity>,
    @InjectEntityManager() private entityManager: EntityManager,
    private readonly httpService: HttpService,
    private readonly configService: ConfigService
  ){}

  async getOtherHalfInfoBySysID(UserSysID:number){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const list = await this.userExtendEntityRepository
        .createQueryBuilder('UE')
        .select([
          'UE.SysID SysID','UE.UserSysID UserSysID','UE.OtherHalfSysID OtherHalfSysID','A.AvatarUrl UserAvatarUrl',
          'HU.NickName OtherHalfNickName','AO.AvatarUrl OtherHalfAvatarUrl','UE.IsSingle IsSingle','UE.IsSign IsSign',
          'UE.CouplesMoney CouplesMoney','UE.ContinueSign ContinueSign','U.Birthday Birthday',
          'CASE WHEN UE.IsSingle=0 THEN U.Birthday ELSE UE.LoveDate END LoveDate'
        ])
        .leftJoin('Avatar','A','UE.UserSysID=A.UserSysID')
        .leftJoin('User','U','UE.UserSysID=U.SysID')
        .leftJoin('Avatar','AO','UE.OtherHalfSysID=AO.UserSysID')
        .leftJoin('User','HU','UE.OtherHalfSysID=HU.SysID')
        .where('UE.Deleted=0 AND A.Deleted=0 ')
        .andWhere('UE.UserSysID=:UserSysID',{UserSysID:UserSysID})
        .limit(1)
        .getRawOne();
      resData.data=list;
      resData.msg='获取另一半信息成功!'
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取另一半信息失败!'
      }
    }
    return resData;
  }

  async getUserOpenID(param:GetUserOpenIDDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {JsCode}=param
      const wxUrl=this.configService.get('WECHAT_CONFIG').url
      const appid=this.configService.get('WECHAT_CONFIG').appid
      const secret=this.configService.get('WECHAT_CONFIG').secret
      const resOpenID = await this.httpService.axiosRef.get(`
        ${wxUrl}/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${JsCode}&grant_type=authorization_code
      `)
      if(resOpenID.status===200){
        const {openid=''}=resOpenID.data
        const UserEntityList = await this.userEntityRepository 
          .createQueryBuilder('U')
          .select(['U.SysID SysID','U.NickName NickName','A.AvatarUrl AvatarUrl'])
          .leftJoin('Avatar','A','U.SysID=A.UserSysID')
          .where('U.OpenID=:OpenID AND A.Deleted=0 AND U.Deleted=0 ',{
            OpenID:openid
          })
          .getRawMany()
        if(UserEntityList.length===0){
          resData.data={
            ExistUser:false,
            OpenID:openid
          }
        }
        else{
          resData.data={
            ExistUser:true,
            OpenID:openid,
            UserInfo:UserEntityList[0]
          }
        }
      }
      else{
        resData={
          code:500,
          data:{
            
          },
          msg:'调取微信接口返回数据失败!'
        }
      }

    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取用户的OpenID失败'
      }
    }
    
    return resData
  }

  async sendRegisterSmsCode(sendRegisterSmsCode:SendRegisterSmsCodeDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {Phone}=sendRegisterSmsCode;
      const smscode=RandomCode(4)+'';
      const now=dayjs().format('YYYY-MM-DD HH:mm:ss')
      await sendSms(Phone,'1537525',[smscode,'5'])
        .then(async res=>{
          const newSmsCodeEntity=new SmsCodeEntity();
          newSmsCodeEntity.Mobile=Phone;
          newSmsCodeEntity.SmsCode=smscode;
          newSmsCodeEntity.Source='register';
          newSmsCodeEntity.CreateTime=now;
          newSmsCodeEntity.UpdateTime=now;
          newSmsCodeEntity.Deleted=0;
          await this.smsCodeEntityRepository.save(newSmsCodeEntity);
          resData=res as any
        })
        .catch(error=>{
          resData=error
        })
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'发送验证码失败!'
      }
      
    }
    return resData
  }

  async registerUser(registerUser:RegisterUserDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {OpenID,NickName,Birthday,LunarBirthday,LunarNumBirthday,SolarBirthday,
        LunarOrSolar,Gender,Horoscope,Mobile,SmsCode='',AvatarUrl
      }=registerUser;
      //判断手机号跟验证码是否一致
      const smsCodeList=await this.smsCodeEntityRepository.find({
        select:['CreateTime'],
        where:{
          Mobile:Mobile,
          SmsCode:SmsCode,
          Source:'register',
          Deleted:0
        }
      })
      if(smsCodeList.length>0){
        const ExpiresTime=dayjs(smsCodeList[0].CreateTime).add(300,'s').format('YYYY-MM-DD HH:mm:ss');
        if(dayjs().diff(dayjs(ExpiresTime),'s')>0){
          resData.code=400;
          resData.msg='验证码已过期!'
          const newSmsCode=new SmsCodeEntity();
          newSmsCode.Deleted=1;
          newSmsCode.UpdateTime=dayjs().format('YYYY-MM-DD HH:mm:ss')
          await this.smsCodeEntityRepository.update({
            Mobile:Mobile,
            Source:'register',
            Deleted:0
          },newSmsCode)
        }
        else{
          //判断用户是否已注册
          const UserList=await this.userEntityRepository.find({
            select:['SysID'],
            where:{
              OpenID:OpenID,
              Deleted:0
            }
          })
          if(UserList.length>0){
            resData.code=400;
            resData.msg='您已注册请返回直接登录'
            const newSmsCode=new SmsCodeEntity();
            newSmsCode.Deleted=1;
            newSmsCode.UpdateTime=dayjs().format('YYYY-MM-DD HH:mm:ss')
            await this.smsCodeEntityRepository.update({
              Mobile:Mobile,
              Source:'register',
              Deleted:0
            },newSmsCode)
          }
          else{
            const now=dayjs().format('YYYY-MM-DD HH:mm:ss');
            await this.entityManager.transaction(async entityManager=>{
              //#region 插入用户表
              const newUserEntity=new UserEntity()
              newUserEntity.OpenID=OpenID;
              newUserEntity.NickName=NickName;
              newUserEntity.Birthday=Birthday;
              newUserEntity.LunarBirthday=LunarBirthday;
              newUserEntity.LunarNumBirthday=LunarNumBirthday;
              newUserEntity.SolarBirthday=SolarBirthday;
              newUserEntity.LunarOrSolar=LunarOrSolar;
              newUserEntity.Mobile=Mobile;
              newUserEntity.Gender=Gender;
              newUserEntity.Horoscope=Horoscope;
              newUserEntity.CreateTime=now;
              newUserEntity.UpdateTime=now;
              newUserEntity.Deleted=0;
              const newUser=await entityManager.save(UserEntity,newUserEntity);
              //#endregion
              
              //#region 插入头像表
              const newAvatarEntity=new AvatarEntity();
              newAvatarEntity.UserSysID=newUser.SysID;
              newAvatarEntity.AvatarUrl=AvatarUrl;
              newAvatarEntity.AvatarBase='';
              newAvatarEntity.CreateTime=now;
              newAvatarEntity.UpdateTime=now;
              newAvatarEntity.Deleted=0;
              await entityManager.save(AvatarEntity,newAvatarEntity)
              //#endregion
              
              //#region 插入拓展表
              const newUserExtendEntity=new UserExtendEntity()
              newUserExtendEntity.UserSysID=newUser.SysID;
              newUserExtendEntity.OtherHalfSysID=-1;
              newUserExtendEntity.CouplesMoney=0;
              newUserExtendEntity.ContinueSign=0;
              newUserExtendEntity.SignDay=0;
              newUserExtendEntity.IsSign=0;
              newUserExtendEntity.LoveDate='';
              newUserExtendEntity.IsSingle=0;
              newUserExtendEntity.LoveCode=RandomCode(8)+'';
              newUserExtendEntity.EditedCommemorationDay=0;
              newUserExtendEntity.CreateTime=now;
              newUserExtendEntity.UpdateTime=now;
              newUserExtendEntity.Deleted=0;
              await entityManager.save(UserExtendEntity,newUserExtendEntity)
              //#endregion

              //#region 插入初始纪念日
              const userCommemorationDayList = await entityManager.find(UserCommemorationDayEntity,{
                where:{
                  UserSysID:newUser.SysID
                }
              })
              if(userCommemorationDayList.length===0){
                await entityManager.query(`
                  INSERT INTO UserCommemorationDay(
                      BaseSysID,UserSysID,CommemorationName,SingleCommemorationName,
                      BaseCommemorationDate,CommemorationDate,LunarDate,LunarNumDate,SolarDate,IntervalDay,LunarOrSolar,Weekly,
                      RemindDate,RemindTime,Circulation,Edited,UpdateDate,CountDown,SendSmsIntervalDate,CreateTime,UpdateTime,Deleted
                  )
                  SELECT SysID,'${newUser.SysID}',CommemorationName,SingleCommemorationName,
                      CommemorationDate,CommemorationDate,LunarDate,LunarNumDate,SolarDate,IntervalDay,LunarOrSolar,Weekly,
                      RemindDate,RemindTime,Circulation,0,UpdateDate,CountDown,SendSmsIntervalDate,'${now}','${now}',0
                  FROM BaseCommemorationDay
                  WHERE Deleted=0
                `)
              }
              //#endregion

              //#region 插入初始化小事
              const userLittleThingsList=await entityManager.find(UserLittleThingsEntity,{
                where:{
                  UserSysID:newUser.SysID
                }
              })
              if(userLittleThingsList.length===0){
                await entityManager.query(`
                  INSERT INTO UserLittleThings (BaseSysID,UserSysID,ThingName,ImageUrl,ThingContent,Edited,IsCompleted,CreateTime,UpdateTime,Deleted)
                  SELECT SysID,'${newUser.SysID}',ThingName,ImageUrl,ThingContent,0,0,'${now}','${now}',0
                  FROM BaseLittleThings
                `)
              }
              //#endregion
              
              //#region 删除验证码表
              const newSmsCode=new SmsCodeEntity();
              newSmsCode.Deleted=1;
              newSmsCode.UpdateTime=dayjs().format('YYYY-MM-DD HH:mm:ss')
              await entityManager.update(SmsCodeEntity,{
                Mobile:Mobile,
                Source:'register',
                Deleted:0
              },newSmsCode)
              //#endregion

              resData.data={
                UserSysID:newUser.SysID
              }
              resData.msg='注册成功!'
            })
          }
        }
      }
      else{
        resData.code=400;
        resData.msg='验证码不正确!'
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'注册用户失败!'
      }
    }
    return resData
  }

  async uploadAvatar(uploadAvatar:UploadAvatarDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    await uploadFile(
      uploadAvatar.AvatarFile,
      'base64',
      'avatar/'
    )
      .then((res:{
        code:number,
        data:any,
        msg:string
      })=>{
        if(res.code===200){
          resData={
            code:200,
            data:{
              ImageUrl: `http://${res.data.ImageUrl}`,
            },
            msg:'保存头像成功!'
          }
        }
        else{
          resData={
            code:500,
            data:{
              res
            },
            msg:'保存头像失败!'
          }
        }
      })
      .catch(e=>{
        resData={
          code:500,
          data:{
            e
          },
          msg:'保存头像失败!'
        }
      })
    return resData
  }

  async userSignIn(userSignIn:UserSignInDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {UserSysID=-1}=userSignIn
      if(UserSysID===-1){
        resData.code=400;
        resData.msg='未获取到用户ID'
      }
      else{
        const yesterday=dayjs().add(-1, 'day').format('YYYY-MM-DD');
        const today=dayjs().format('YYYY-MM-DD');
        const now=dayjs().format('YYYY-MM-DD HH:mm:ss');
        await this.entityManager.transaction(async entityManager=>{
          //获取昨天是否签到
          const yesterdayIsSign=await entityManager.find(UserSignDataEntity,{
            where:{
              SignDate:yesterday,
              Deleted:0
            }
          })
          //#region 插入UserSignData表
          const newUserSignDataEntity=new UserSignDataEntity();
          newUserSignDataEntity.UserSysID=UserSysID;
          newUserSignDataEntity.SignDate=today;
          newUserSignDataEntity.CreateTime=now;
          newUserSignDataEntity.UpdateTime=now;
          newUserSignDataEntity.Deleted=0;
          await entityManager.save(UserSignDataEntity,newUserSignDataEntity);
          //#endregion
          const CouplesMoney = RandomCode(1);
          //#region 处理UserExtend表
          if(yesterdayIsSign.length>0){
            //昨天已签到
            await entityManager.query(`
              UPDATE UserExtend 
              SET ContinueSign=ContinueSign+1,CouplesMoney=CouplesMoney+${CouplesMoney},SignDay=SignDay+1,IsSign=1,UpdateTime='${now}' 
              WHERE UserSysID='${UserSysID}' AND Deleted=0;
            `)
          }
          else{
            //昨天未签到
            await entityManager.query(`
              UPDATE UserExtend 
              SET ContinueSign=1,CouplesMoney=CouplesMoney+${CouplesMoney},SignDay=SignDay+1,IsSign=1,UpdateTime='${now}' 
              WHERE UserSysID='${UserSysID}' AND Deleted=0;
            `)
          }
          //#endregion
        })

        const userSignData= await this.userExtendEntityRepository.findOne({
          select:[
            'ContinueSign',
            'CouplesMoney'
          ],
          where:{
            UserSysID:UserSysID,
            Deleted:0
          }
        })
        resData.data=userSignData;
        resData.msg='用户签到成功!'
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'用户签到失败!'
      }
    }
    return resData
  }

  async getUserLimit(getUserLimit:GetUserLimitDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {LimitName=''}=getUserLimit
      const userLimitList=await this.userLimitEntityRepository.find({
        select:['SysID','LimitName','Title','Url','Enable'],
        where:{
          LimitName:LimitName,
          Deleted:0
        }
      })
      resData.data={
        limitList:userLimitList
      }
      resData.msg='获取权限成功!'
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取权限失败!'
      }
    }
    return resData
  }

  async getUserHoroscope(getUserHoroscope:GetUserHoroscopeDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {UserSysID=-1}=getUserHoroscope;
      const horoscope = await this.horoscopeEntityRepository
        .createQueryBuilder('H')
        .select([
          'H.SysID SysID','H.Name Name','H.Date Date','H.Health Health','H.Love Love',
          'H.Money Money','H.Work Work','H.Icon Icon'
        ])
        .innerJoin('User','U','U.Horoscope=H.Name AND U.Deleted=0 ')
        .where('H.Deleted=0')
        .andWhere('U.SysID=:UserSysID',{UserSysID:UserSysID})
        .getRawOne()
      resData.data=horoscope;
      resData.msg='获取星座信息成功!'
      return resData
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取星座运势失败!'
      }
    }
    return resData

  }

  async submitFeedBack(submitFeedBack:SubmitFeedBackDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {UserSysID=-1,Content='',ImageData=[]}=submitFeedBack
      if(Content===''){
        resData.code=400;
        resData.msg='反馈内容不能为空';
      }
      else{
        const now=dayjs().format('YYYY-MM-DD HH:mm:ss')
        await this.entityManager.transaction(async entityManager=>{

          //#region 插入反馈主表
          const newFeedBackEntity=new FeedBackEntity();
          newFeedBackEntity.UserSysID=UserSysID;
          newFeedBackEntity.Content=Content;
          newFeedBackEntity.CreateTime=now;
          newFeedBackEntity.UpdateTime=now;
          newFeedBackEntity.Deleted=0;
          const newFeedBack = await entityManager.save(FeedBackEntity,newFeedBackEntity);
          //#endregion

          //#region 插入反馈图片表
          let sort=0;
          for (const item of ImageData) {
            sort=sort+1;
            const resImage=await uploadFile(item,'base64','feedback/') as {code:number,data:any,msg:string};
            if(resImage.code===200){
              const newFeedBackImageEntity=new FeedBackImageEntity();
              newFeedBackImageEntity.BaseSysID=newFeedBack.SysID;
              newFeedBackImageEntity.ImageUrl=resImage.data.ImageUrl
              newFeedBackImageEntity.Sort=sort;
              newFeedBackImageEntity.CreateTime=now;
              newFeedBackImageEntity.UpdateTime=now;
              newFeedBackImageEntity.Deleted=0;
              await entityManager.save(FeedBackImageEntity,newFeedBackImageEntity)
            }
          }
          //#endregion
        })
        resData.code=200;
        resData.msg='提交反馈成功!'
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'提交反馈失败!'
      }
    } 
    return resData
  }

  async getUserLoveCode(getUserLoveCode:GetUserLoveCodeDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {UserSysID=-1}=getUserLoveCode;
      const loveCode=await this.userExtendEntityRepository.findOne({
        select:['LoveCode'],
        where:{
          UserSysID:UserSysID,
          Deleted:0
        }
      })
      resData.data=loveCode
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取恋爱密码失败!'
      }
    }
    return resData
  }

  async getUserInfoByLoveCode(getUserInfoByLoveCode:GetUserInfoByLoveCodeDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {LoveCode=''}=getUserInfoByLoveCode;
      const userInfo=await this.userExtendEntityRepository
        .createQueryBuilder('UE')
        .select([
          'UE.SysID SysID','U.SysID UserSysID','U.NickName NickName','A.AvatarUrl AvatarUrl','UE.IsSingle IsSingle'
        ])
        .innerJoin('User','U','UE.UserSysID=U.SysID AND U.Deleted=0')
        .innerJoin('Avatar','A','UE.UserSysID=A.UserSysID AND A.Deleted=0')
        .where('UE.LoveCode=:LoveCode AND UE.Deleted=0',{LoveCode:LoveCode})
        .getRawMany();
      if(userInfo.length>0){
        if(userInfo[0].IsSingle===0){
          resData.data={
            ...userInfo[0]
          }
        }
        else{
          resData.code=400;
          resData.msg='您绑定的用户非单身状态'
        }
      }
      else{
        resData.code=400;
        resData.msg='恋爱密码输入不正确!'
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取信息失败!'
      }
    }
    return resData;
  }

  async bindUserOtherHalf(bindUserOtherHalf:BindUserOtherHalfDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {UserSysID=-1,OtherHalfUSerID=-1,LoveDate}=bindUserOtherHalf
      if(UserSysID===-1){
        resData.code=400;
        resData.msg='未获取到您的个人信息'
      }
      else if(OtherHalfUSerID===-1){
        resData.code=400;
        resData.msg='未获取到您绑定的用户信息'
      }
      else{
        const now=dayjs().format('YYYY-MM-DD HH:mm:ss')
        //先判断是否单身
        const isSingleCount = await this.userExtendEntityRepository.count({
          where:([
            {
              UserSysID:UserSysID,
              IsSingle:0,
              Deleted:0
            },
            {
              UserSysID:OtherHalfUSerID,
              IsSingle:0,
              Deleted:0
            }
          ])
        })
        if(isSingleCount===2){
          const loveCodeInfo = await this.entityManager.findOne(UserExtendEntity,{
            select:['LoveCode'],
            where:{
              UserSysID:UserSysID,
              Deleted:0
            }
          })
          const {LoveCode}=loveCodeInfo;
          const newUserExtendEntity=new UserExtendEntity();
          newUserExtendEntity.UpdateTime=now;
          newUserExtendEntity.LoveDate=LoveDate;
          newUserExtendEntity.LoveCode=LoveCode;
          newUserExtendEntity.OtherHalfSysID=OtherHalfUSerID;
          newUserExtendEntity.IsSingle=1
          await this.entityManager.update(UserExtendEntity,{
            UserSysID:UserSysID,
            Deleted:0
          },newUserExtendEntity)
          const newOtherHalfUserExtendEntity=new UserExtendEntity();
          newOtherHalfUserExtendEntity.UpdateTime=now;
          newOtherHalfUserExtendEntity.LoveDate=LoveDate;
          newOtherHalfUserExtendEntity.LoveCode=LoveCode;
          newOtherHalfUserExtendEntity.OtherHalfSysID=UserSysID;
          newOtherHalfUserExtendEntity.IsSingle=1
          await this.entityManager.update(UserExtendEntity,{
            UserSysID:OtherHalfUSerID,
            Deleted:0
          },newOtherHalfUserExtendEntity)
        }
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:''
      }
    }
    return resData
  }

  async handleUser(handleUser:HandleUserDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {UserSysID=-1,NickName,Birthday,LunarBirthday,LunarNumBirthday,SolarBirthday,
        LunarOrSolar,Gender,Horoscope,Mobile,SmsCode='',AvatarUrl
      }=handleUser;
      //判断手机号跟验证码是否一致
      const smsCodeList=await this.smsCodeEntityRepository.find({
        select:['CreateTime'],
        where:{
          Mobile:Mobile,
          SmsCode:SmsCode,
          Source:'register',
          Deleted:0
        }
      })
      if(smsCodeList.length>0){
        const ExpiresTime=dayjs(smsCodeList[0].CreateTime).add(300,'s').format('YYYY-MM-DD HH:mm:ss');
        if(dayjs().diff(dayjs(ExpiresTime),'s')>0){
          resData.code=400;
          resData.msg='验证码已过期!'
          const newSmsCode=new SmsCodeEntity();
          newSmsCode.Deleted=1;
          newSmsCode.UpdateTime=dayjs().format('YYYY-MM-DD HH:mm:ss')
          await this.smsCodeEntityRepository.update({
            Mobile:Mobile,
            Source:'register',
            Deleted:0
          },newSmsCode)
        }
        else{
          if(UserSysID===-1){
            resData.code=400;
            resData.msg='未获取到您的用户信息'
          }
          else{
            const now=dayjs().format('YYYY-MM-DD HH:mm:ss');
            await this.entityManager.transaction(async entityManager=>{
              const updateUserEntity=new UserEntity()
              updateUserEntity.NickName=NickName;
              updateUserEntity.Birthday=Birthday;
              updateUserEntity.LunarBirthday=LunarBirthday;
              updateUserEntity.LunarNumBirthday=LunarNumBirthday;
              updateUserEntity.SolarBirthday=SolarBirthday;
              updateUserEntity.LunarOrSolar=LunarOrSolar;
              updateUserEntity.Mobile=Mobile;
              updateUserEntity.Gender=Gender;
              updateUserEntity.Horoscope=Horoscope;
              updateUserEntity.UpdateTime=now;
              await entityManager.update(UserEntity,{
                SysID:UserSysID,
                Deleted:0
              },updateUserEntity);

              //#region 更新头像表
              const updateAvatarEntity=new AvatarEntity();
              updateAvatarEntity.AvatarUrl=AvatarUrl;
              updateAvatarEntity.AvatarBase='';
              updateAvatarEntity.UpdateTime=now;
              await entityManager.update(AvatarEntity,{
                UserSysID:UserSysID,
                Deleted:0
              },updateAvatarEntity)
              //#endregion

              //#region 删除验证码表
              const updateSmsCode=new SmsCodeEntity();
              updateSmsCode.Deleted=1;
              updateSmsCode.UpdateTime=now
              await entityManager.update(SmsCodeEntity,{
                Mobile:Mobile,
                Source:'register',
                Deleted:0
              },updateSmsCode)
              //#endregion

            })
            
            resData.msg='更新成功!'
          }
          
        }
      }
      else{
        resData.code=400;
        resData.msg='验证码不正确!'
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'注册用户失败!'
      }
    }
    return resData
  }

  async getUserInfoBySysID(getUserInfoBySysID:GetUserInfoBySysIDDTO){
    let resData={
      code:200,
      data:{},
      msg:''
    }
    try{
      const {UserSysID=-1}=getUserInfoBySysID
      if(UserSysID===-1){
        resData.code=400;
        resData.msg='暂未获取到用户信息'
      }
      else{
        const userInfo = await this.userEntityRepository
          .createQueryBuilder('U')
          .select([
            'U.SysID UserSysID','U.NickName NickName','U.Birthday Birthday','U.LunarBirthday LunarBirthday',
            'U.LunarOrSolar LunarOrSolar','U.Gender Gender','U.Mobile Mobile','A.AvatarUrl AvatarUrl'
          ])
          .leftJoin('Avatar','A','U.SysID=A.UserSysID AND A.Deleted=0')
          .where(' U.SysID=:UserSysID AND U.Deleted=0',{UserSysID:UserSysID})
          .getRawOne()
        resData.data=userInfo
        resData.msg='获取用户信息成功!'
      }
    }
    catch(e){
      resData={
        code:500,
        data:{
          e
        },
        msg:'获取用户信息失败!'
      }
    }
    return resData
  }

}
